package com.fingard.dsp.bank.directbank.xwbank02;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.xwbank.sdk.XWBankPay;
import com.xwbank.sdk.entity.SingleCollectionInfo;
import com.xwbank.sdk.entity.SingleTransStatusQueryInfo;

public class XWBank02RealTime extends XWBank02Base implements IRealTime {
	@Override
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108)	throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		String propertiesPath = getBankConfig().getValueAsString("propertiesPath");
		String merchantId = getBankConfig().getValueAsString("merchantId");
		String ownKeyStorePath = getBankConfig().getValueAsString("ownKeyStorePath");
		if (StringHelper.isNullOrEmpty(propertiesPath) || StringHelper.isNullOrEmpty(merchantId) || StringHelper.isNullOrEmpty(ownKeyStorePath)) {
			tmpRetDetail.respCode = "0";
			tmpRetDetail.respInfo = "缺失'propertiesPath/merchantId/ownKeyStorePath'配置或节点内容为空!";
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
			tmpRetDetail.transState = PaymentState.FAIL_Payment;
			tmpRetDetail.payInfoCode = FailCode.E9981;
			retAts.writeRetDetail(tmpRetDetail);
			return retAts;
		}
		
		boolean initSuccess = XWBankPay.init(getConfigPath(propertiesPath), getConfigPath(ownKeyStorePath));
		if (!initSuccess) {
			tmpRetDetail.respCode = "0";
			tmpRetDetail.respInfo = "config.properties配置有误!";
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
			tmpRetDetail.transState = PaymentState.FAIL_Payment;
			tmpRetDetail.payInfoCode = FailCode.E9981;
			retAts.writeRetDetail(tmpRetDetail);
			return retAts;
		}
		
		SingleCollectionInfo recSubmitRequest = new SingleCollectionInfo();
		
		recSubmitRequest.setVersion("1.0");
		recSubmitRequest.setMcht_no(merchantId);
		recSubmitRequest.setTran_no(p_req9108.singleDetail.askNumber);
		
		recSubmitRequest.setPriority("HIGH");// 实时
		recSubmitRequest.setPayee_acct_no(p_req9108.singleDetail.recAct);
		recSubmitRequest.setPayee_acct_name(p_req9108.singleDetail.recName);
		recSubmitRequest.setPayer_acct_no(p_req9108.singleDetail.payAct);
		String cardType = "";
		if (!"1".equals(p_req9108.singleDetail.isPrivate)) {
			cardType = "PUBLIC";// 对公账户
		} else if ("3".equals(p_req9108.singleDetail.cardType)) {
			cardType = "CREDIT";// 信用卡
		} else {
			cardType = "DEBIT";// 借记卡
		}
		recSubmitRequest.setPayer_acct_type(cardType);
		recSubmitRequest.setPayer_acct_name(p_req9108.singleDetail.payName);
		recSubmitRequest.setPayer_op_bank_code(p_req9108.singleDetail.cnapsCode);
		recSubmitRequest.setPayer_phone(p_req9108.singleDetail.cellPhone);
		recSubmitRequest.setPayer_cer_type("B01");// 身份证
		recSubmitRequest.setPayer_cer_no(p_req9108.singleDetail.certNum);
		recSubmitRequest.setCcy("CNY");
		recSubmitRequest.setAmt(p_req9108.singleDetail.payAmount);
		recSubmitRequest.setRemark(p_req9108.singleDetail.useType);
		String purpose = p_req9108.singleDetail.purpose;
		if (StringHelper.isNullOrEmpty(purpose)) {
			purpose = p_req9108.singleDetail.memo;
		}
		if (StringHelper.isNullOrEmpty(purpose)) {
			purpose = p_req9108.singleDetail.abstractATS;
		}
		recSubmitRequest.setPurpose(purpose);
		recSubmitRequest.setMsg_spare("00001");// 指定账户
		
		writeBankLogStep2(recSubmitRequest);
		
		Map<String, Object> tmpMapRet = XWBankPay.getInstance().singleCollection(recSubmitRequest);
		
		writeBankLogStep3(tmpMapRet);
		
		if (tmpMapRet != null) {
			tmpRetDetail.respCode = "0";
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
			tmpRetDetail.respInfo = (String) tmpMapRet.get("returnMsg");
			
			String tmpRespCode = (String) tmpMapRet.get("returnCode");
			if ("000000".equals(tmpRespCode)) {
				JSONObject tmpJsonRet = JSONObject.parseObject((String) tmpMapRet.get("data"));
				
				String returnCode = tmpJsonRet.getString("return_code");
				String returnMsg = tmpJsonRet.getString("return_message");
				String dealResult = tmpJsonRet.getString("deal_result");
				if (StringHelper.hasAnyChar(dealResult)) {
					tmpRetDetail.transState = StringHelper.joinNotEmpty("+", tmpRespCode, dealResult);
					tmpRetDetail.payInfoCode = returnCode;
				} else {
					// 无状态字符返回可能是参数格式有误、网络异常等
					tmpRetDetail.transState = returnCode;
					tmpRetDetail.payInfoCode = returnCode;
				}
				tmpRetDetail.respInfo = returnMsg;
			} else {
				// 网关错误也需要使用查询接口查回最终状态再判定支付状态
				tmpRetDetail.transState = tmpRespCode;
				tmpRetDetail.payInfoCode = tmpRespCode;
			}
		} else {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = "银行返回内容为空!";
		}

		if ("-1".equals(tmpRetDetail.respCode)	&& StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

		try {
			String propertiesPath = getBankConfig().getValueAsString("propertiesPath");
			String merchantId = getBankConfig().getValueAsString("merchantId");
			String ownKeyStorePath = getBankConfig().getValueAsString("ownKeyStorePath");
			if (StringHelper.isNullOrEmpty(propertiesPath) || StringHelper.isNullOrEmpty(merchantId) || StringHelper.isNullOrEmpty(ownKeyStorePath)) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "缺失'propertiesPath/merchantId/ownKeyStorePath'配置或节点内容为空!";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			boolean initSuccess = XWBankPay.init(getConfigPath(propertiesPath), getConfigPath(ownKeyStorePath));
			if (!initSuccess) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "config.properties配置有误!";
				tmpRetDetail.reqSeqID = p_req9144.askNumber;
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			SingleTransStatusQueryInfo recQueryRequest = new SingleTransStatusQueryInfo();
			
			recQueryRequest.setVersion("1.0");
			recQueryRequest.setMcht_no(merchantId);
			recQueryRequest.setOrig_tran_no(p_req9144.askNumber);
			recQueryRequest.setAcct_no(p_req9144.payAct);
			recQueryRequest.setBiz_type("02");// 单笔代收
			
			writeBankLogStep2(recQueryRequest);
			
			Map<String, Object> tmpMapRet = XWBankPay.getInstance().singleTransStatusQuery(recQueryRequest);
			
			writeBankLogStep3(tmpMapRet);
			
			if (tmpMapRet != null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.reqSeqID = p_req9144.askNumber;
				
				String tmpRespCode = (String) tmpMapRet.get("returnCode");
				String tmpRespInfo = (String) tmpMapRet.get("returnMsg");
				if ("000000".equals(tmpRespCode)) {
					JSONObject tmpJsonRet = JSONObject.parseObject((String) tmpMapRet.get("data"));
					
					String returnCode = tmpJsonRet.getString("return_code");
					String returnMsg = tmpJsonRet.getString("return_message");
					String dealResult = tmpJsonRet.getString("orig_deal_result");
					if (StringHelper.hasAnyChar(dealResult)) {
						tmpRetDetail.transState = StringHelper.joinNotEmpty("+", tmpRespCode, dealResult);
						tmpRetDetail.payInfoCode = returnCode;
						tmpRetDetail.respInfo = returnMsg;
						if ("4".equals(dealResult)) { // 无此交易
							if (canBeNotExist(p_req9144, tmpRetDetail, 10)) {
								tmpRetDetail.payInfoCode = returnMsg;
							}
						}
					} else {
						// 无状态字符返回可能是参数格式有误、网络异常等
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = returnMsg;
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpRespInfo;
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "银行返回内容为空!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		if (tmpRetDetail.respCode.equals("-1")	&& StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9144.askNumber;
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
